package cn.tedu.search.service;

import com.jt.common.pojo.Product;
import com.jt.common.utils.MapperUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchService {
    @Autowired
    RestHighLevelClient highLevelClient;

    public List<Product> search(String text, Integer page, Integer rows) {
        List<Product> productList = null;
        SearchRequest searchRequest = new SearchRequest("easyindex");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("productName", text));
        searchSourceBuilder.from((page-1) * rows);
        searchSourceBuilder.size(rows);
        searchRequest.source(searchSourceBuilder);
        searchRequest.scroll(TimeValue.timeValueMinutes(1L)); //设置scroll间隔
        try {
            SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits topHits = searchResponse.getHits();  //检索第一批搜索命中
            SearchHit[] hits = topHits.getHits();// 第二层hits是个数组
            productList = new ArrayList<>();
            for (SearchHit hit : hits) {
                // 每循环一次，都可以从hit中拿到source字符串productJson
                String productJson = hit.getSourceAsString();
                // 从字符串转化为对象的过程
                // 传递参数json字符串，和转化对象类的反射
                Product product = MapperUtil.MP.readValue(productJson, Product.class);
                // 加到商品队列中
                productList.add(product);
            }

        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            return productList;
        }
    }
}
